<template>
<!-- WIFI设置 -->

  <div class="ethernet-settings">
    <div class="top-box">
      <v-container fluid>
        <v-row align="center">
          <v-col cols="4" class="d-flex justify-center text-center">
            <div class="config-item">
              WIFI名
            </div>
          </v-col>
          <v-col cols="8" class="d-flex text-center">
            <v-select
                v-model="wifiName"
                label="请选择WIFI"
                class="config-content"
                :items="wifiList"
                item-text="txt"
                item-value="txt"
                dense
                @change="checkWifi()"
                :error-messages="wifiNameError ? [wifiNameError] : []"
                hide-details
                no-data-text="未检测到可用WIFI"
                outlined
                :menu-props="{
                  offsetY: true,
                  maxHeight: '300'
                }"
            ></v-select>
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="4" class="d-flex justify-center text-center">
            <div class="config-item">
              WIFI密码
            </div>
          </v-col>
          <v-col cols="8" class="d-flex text-center">
            <v-text-field
                :type="showPassword ? 'text' : 'password'"
                v-model="wifiPwd"
                label="请输入密码"
                class="config-content"
                dense
                hide-details
                outlined
                @change="checkWifi()"
                :error-messages="wifiPasswordError ? [wifiPasswordError] : []"
                :append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
                @click:append="togglePasswordVisibility"></v-text-field>
          </v-col>
        </v-row>
        <v-row align="center" justify="center" class="button-container">
          <v-col cols="12" class="text-center">
            <v-btn @click="openMore" class="mx-2"
                   style="background-color: transparent; border: none; box-shadow: none; padding: 0; text-transform: none !important">
              <v-icon left>mdi-cog</v-icon>
              高级设置
            </v-btn>
          </v-col>
        </v-row>
      </v-container>
    </div>
    <div class="bottom-box">
      <v-btn @click="refresh" class="refresh-btn"
             style="background-color: #003366; color: white; margin-right: 10px;">刷新
      </v-btn>
      <v-btn class="save-btn" @click="save" style="background-color: #FFA500; color: white;">保存</v-btn>
    </div>
    <v-dialog
        v-model="dialog"
        persistent
        content-class="text-center"
        max-width="800"
        class="settings-dialog">
      <v-card>
        <v-card-title class="headline text-h5 settings-title">
          <div class="title-content">WIFI高级设置</div>
        </v-card-title>
        <v-card-actions class="settings-content">
          <v-container>
            <v-row align="center">
              <v-col cols="4" class="d-flex justify-center text-center">
                <div class="config-item">
                  IP地址
                </div>
              </v-col>
              <v-col cols="8" class="d-flex text-center">
                <v-text-field
                    v-model="temp.wifiIpAddress"
                    label="192.168.100.20"
                    class="config-content justify-center"
                    dense
                    :disabled=temp.autoGetWifiIp
                    hide-details></v-text-field>
              </v-col>
            </v-row>
            <v-row align="center">
              <v-col cols="4" class="d-flex justify-center text-center">
                <div class="config-item">
                  默认网关
                </div>
              </v-col>
              <v-col cols="8" class="d-flex text-center">
                <v-text-field
                    v-model="temp.wifiDefaultGateway"
                    label="192.168.100.1"
                    class="config-content"
                    dense
                    :disabled=temp.autoGetWifiIp
                    hide-details></v-text-field>
              </v-col>
            </v-row>
            <v-row align="center">
              <v-col cols="4" class="d-flex justify-center text-center">
                <div class="config-item">
                  子网掩码
                </div>
              </v-col>
              <v-col cols="8" class="d-flex text-center">
                <v-text-field
                    v-model="temp.wifiMask"
                    label="255.255.0.0"
                    class="config-content"
                    dense
                    :disabled=temp.autoGetWifiIp
                    hide-details></v-text-field>
              </v-col>
            </v-row>
            <v-row align="center" justify="center">
              <v-checkbox
                  v-model="temp.autoGetWifiIp"
                  dense
                  label="自动获取IP地址"></v-checkbox>
            </v-row>
            <v-row>
              <v-col cols="4"></v-col>
              <v-col cols="2">
                <v-btn @click="dialog = false" style="background-color: #003366; color: white; margin-right: 10px;">
                  取消
                </v-btn>
              </v-col>
              <v-col cols="2">
                <v-btn @click="sure" style="background-color: #FFA500; color: white;">确定</v-btn>
              </v-col>
              <v-col cols="4"></v-col>
            </v-row>
          </v-container>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import sweetalert from 'sweetalert2'

const ipRule = /^(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/
const maskRule = /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(254|252|248|240|224|192|128|0)$/
const gatewayBaseRule = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
// const data = {
//   configValue1: "WLAN0",
//   configValue2: "",
//   configValue3: "",
//   configValue4: "",
//   configValue5: "AE:IE:7F:11:11:11",
//   configValue6: "",
//   configValue7: "",
//   configValue8: ""
// };
export default {
  name: 'EthernetSettingsContent',
  mounted() {
    // setTimeout(()=> {
    //   this.getWifi();
    //   this.intervalId = setInterval(this.getWifi, 5000);
    // }, 180);
  },
  data() {
    return {
      nic: "WLAN0",
      ipAddress: "",
      defaultGateway: "",
      mask: "",
      macAddress: "AE:IE:7F:11:11:11",
      DNS: "",
      wifiName: "",
      wifiPwd: "",
      showPassword: false,
      autoGetIP: true,
      wifiNameError: '',
      wifiPasswordError: '',
      dialog: false,
      temp: {
        wifiIpAddress: '',
        wifiDefaultGateway: '',
        wifiMask: '',
        autoGetWifiIp: true,
      },
      wifiList: [],
      wifiCache: [],
      timeoutDuration: 30000,
    };
  },
  methods: {
    getWifi(networks) {
      console.log(networks)
      this.wifiList = [];
      try {
        networks.forEach((wifi) => {
          if (wifi.ssid !== "") this.wifiList.push({txt: wifi.ssid});
          // this.cacheWifi(wifi);
        })
        // this.wifiCache.forEach((ssid) => {
        //   this.wifiList.push({txt: ssid});
        // })
        // console.log(networks);
      } catch (err) {
        console.log(`there appears error: ${err}`)
      }
    },
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    checkWifi() {
      this.wifiNameError = '';
      this.wifiPasswordError = '';
      if (this.wifiName === '') {
        this.wifiNameError = 'Wifi名不能为空！'
        return true;
      }
      if (this.wifiPwd === '') {
        this.wifiPasswordError = 'Wifi密码不能为空！'
        return true;
      }
      return false;
    },
    refresh() {
      // 刷新逻辑
      this.$emit('refresh')
    },
    openMore() {
      this.dialog = true;
      this.temp.autoGetWifiIp = this.autoGetIP;
      this.temp.wifiDefaultGateway = this.defaultGateway;
      this.temp.wifiMask = this.mask;
      this.temp.wifiIpAddress = this.ipAddress;
    },
    save() {
      if (!this.autoGetIP) {
        if (!ipRule.test(this.ipAddress)) {
          this.$emit('errMsg', 'IP格式有误');
          return;
        } else if (!gatewayBaseRule.test(this.defaultGateway)) {
          this.$emit('errMsg', '网关格式有误');
          return;
        } else if (!maskRule.test(this.mask)) {
          this.$emit('errMsg', '子网掩码格式有误');
          return;
        } else {
          let judgeIp = [];
          let judgeMask = [];
          let judgeGateway = [];
          judgeIp = this.ipAddress.split('.');
          judgeMask = this.mask.split('.');
          judgeGateway = this.defaultGateway.split('.')
          const res0 = parseInt(judgeIp[0]) & parseInt(judgeMask[0]);
          const res1 = parseInt(judgeIp[1]) & parseInt(judgeMask[1]);
          const res2 = parseInt(judgeIp[2]) & parseInt(judgeMask[2]);
          const res3 = parseInt(judgeIp[3]) & parseInt(judgeMask[3]);

          const res0_gw = parseInt(judgeGateway[0]) & parseInt(judgeMask[0]);
          const res1_gw = parseInt(judgeGateway[1]) & parseInt(judgeMask[1]);
          const res2_gw = parseInt(judgeGateway[2]) & parseInt(judgeMask[2]);
          const res3_gw = parseInt(judgeGateway[3]) & parseInt(judgeMask[3]);

          if (!(res0 === res0_gw && res1 === res1_gw && res2 === res2_gw && res3 === res3_gw)) {
            this.$emit('errMsg', '网关配置有误');
            return;
          }
        }
      }
      // 保存逻辑
      if (this.checkWifi()) return;
      const formattedData = {
        "cmd": 242,
        "config": {
          "wlan": {
            [this.nic.toLowerCase()]: {
              'bootproto': this.autoGetIP ? 1 : 0,
              'type': 1,
              'ipaddr': this.ipAddress,
              'mask': this.mask,
              'gateway': this.defaultGateway,
              'wlan-name': this.wifiName,
              'wlan-password': this.wifiPwd
            }
          }
        }
      }
      const jsonData = JSON.stringify(formattedData);
      this.$emit('sendData', jsonData);
    },
    sure() {
      this.autoGetIP = this.temp.autoGetWifiIp;
      this.defaultGateway = this.temp.wifiDefaultGateway;
      this.mask = this.temp.wifiMask;
      this.ipAddress = this.temp.wifiIpAddress;
      this.dialog = false;
    },
    receiveData(data) {
      if (Object.keys(data).length <= 0) {
        // console.log("没有WIFI数据")
        return;
      }
      const wlan0 = data.wlan0;
      sweetalert.fire({
        title: 'WIFI信息',
        html: `WIFI名：${wlan0["wlan-name"]}<br>WIFI密码：${wlan0["wlan-password"]}<br>IP地址：${wlan0.ipaddr}<br>子网掩码：${wlan0.mask}<br>默认网关：${wlan0.gateway}`,
        confirmButtonText: '确定',
        confirmButtonColor: '#3085d6',
        customClass: {
          popup: 'popup-class',
          container: 'container-class'
        }
      });
    },
    cacheWifi(wifi) {
      if (this.wifiCache[wifi.ssid]) {
        clearTimeout(this.wifiCache[wifi.ssid].timerId);
      } else {
        this.wifiCache[wifi.ssid] = {
          timerId: null
        }
      }
      this.wifiCache[wifi.ssid].timerId = setTimeout(() => {
        delete this.wifiCache[wifi.ssid];
        delete this.wifiList[wifi.ssid];
      }, this.timeoutDuration)
    }
  },
  beforeDestroy() {
    // if (this.intervalId) {
    //   clearInterval(this.intervalId);
    // }
  }
};
</script>

<style scoped>
.ethernet-settings::-webkit-scrollbar {
  display: none;
}

.ethernet-settings {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  padding-top: 10vh;
  flex: 1;
  overflow-y: auto;
  scrollbar-width: none;
}

.top-box {
  //padding: 20px;
  box-sizing: border-box;
}

.config-item, .config-content {
  margin-bottom: 10px;
  text-align: center;
}

.bottom-box {
  display: flex;
  justify-content: center;
  padding: 20px;
  width: 100%;
  border-top: 2px solid #ededed;
}

.refresh-btn {
  background-color: #003366;
  color: white;
  margin-right: 10px;
}

.save-btn {
  background-color: #FFA500;
  color: white;
}

.title-content {
  width: 100%;
  text-align: center;
}

.settings-dialog {
  min-width: 700px;
  max-width: 800px;
}

.settings-title {
  border-bottom: 1px solid #ccc;
}

.settings-content {
  justify-content: space-between;
  padding: 0 5vw 0 5vw !important;
}

.popup-class {
  width: 10%;
}

.container-class {
  max-width: 200px;
}
</style>
